﻿using Server.Dto;
using System;
using System.Windows.Forms;

namespace Server.Manage.Components
{
    public partial class ProductHome : Form
    {
        public ProductHome()
        {
            InitializeComponent();
            editingProductBindingSource.DataSource = new ProductDto();
        }

        private void ProductHome_Load(object sender, EventArgs e)
        {
            LoadProducts();
        }

        private void LoadProducts()
        {
            var data = WCFClient.PublishService.Run(t => t.GetProducts());
            productDtoBindingSource.DataSource = data;
        }

        public void MenuItemClick(object sender, EventArgs e)
        {
            if (sender is ToolStripMenuItem item)
            {
                switch (item.Name)
                {
                    case nameof(新增ToolStripMenuItem):
                        editingProductBindingSource.DataSource = new ProductDto();
                        break;
                    case nameof(编辑ToolStripMenuItem):
                        EditProduct();
                        break;
                    case nameof(删除ToolStripMenuItem):
                        DeleteProduct();
                        break;
                }
            }

            if (sender is Button button)
            {
                switch (button.Name)
                {
                    case nameof(button1):
                        if (editingProductBindingSource.DataSource is ProductDto p)
                        {
                            WCFClient.PublishService.Run(t => { t.SaveProduct(p); });
                            LoadProducts();
                        }

                        break;
                }
            }
        }

        public ProductDto GetSelectedProduct()
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                if (dataGridView1.SelectedRows[0].DataBoundItem is ProductDto p)
                {
                    return p;
                }
            }

            return null;
        }

        private void EditProduct()
        {
            var p = GetSelectedProduct();
            if (p != null)
            {
                editingProductBindingSource.DataSource = GetSelectedProduct();
            }
        }

        private void DeleteProduct()
        {
            var p = GetSelectedProduct();
            if (p == null)
            {
                return;
            }

            var dialog = MessageBox.Show("确定删除?", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dialog == DialogResult.OK)
            {
                WCFClient.PublishService.Run(t => { t.DeleteProduct(p); });
                LoadProducts();
            }
        }

    }
}
